﻿// 项目：	Guan.CMS.Domain - Guan.CMS
// 文件名：	UploadProductImageHandler.cs
// 
// 修改时间：2013-03-09 21:55
// 修改人：	Cooclsee

using System.IO;
using System.Web;
using System.Web.Hosting;
using Guan.CMS.CommandProcessor.Command;
using Guan.CMS.Data.Infrastructure;
using Guan.CMS.Data.Repositories;
using Guan.CMS.Domain.Commands.Product;

namespace Guan.CMS.Domain.Handlers.Product
{
    public class UploadProductImageHandler : ICommandHandler<UploadProductImageCommand>
    {
        private readonly IProductRepository _productRepository;
        private readonly IUnitOfWork _unitOfWork;

        public UploadProductImageHandler(IProductRepository productRepository, IUnitOfWork unitOfWork)
        {
            this._productRepository = productRepository;
            this._unitOfWork = unitOfWork;
        }

        public ICommandResult Execute(UploadProductImageCommand command)
        {
            if (command.File != null && command.ProductId > 0)
            {
                //读取Product
                var product = _productRepository.GetById(command.ProductId);
                var ext = Path.GetExtension(command.File.FileName);
                if (!string.IsNullOrWhiteSpace(product.ImageUrl))
                {
                    this.RemoveFile(HostingEnvironment.MapPath(product.ImageUrl));
                }
                var imageUrl = Path.Combine("~/UploadFiles/Products/", product.Id + ext);

                this.SaveFile(command.File, HostingEnvironment.MapPath(imageUrl));
                product.ImageUrl = imageUrl;
                _productRepository.Update(product);
                _unitOfWork.Commit();
                return new CommandResult(true, imageUrl);
            }
            return new CommandResult(false);
        }

        private void RemoveFile(string physicalPath)
        {
            if (!string.IsNullOrWhiteSpace(physicalPath) && File.Exists(physicalPath))
            {
                File.Delete(physicalPath);
            }
        }

        private void SaveFile(HttpPostedFileBase file, string physicalPath)
        {
            var path = Path.GetDirectoryName(physicalPath);
            if (!string.IsNullOrWhiteSpace(path))
            {
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                file.SaveAs(physicalPath);
            }
        }
    }
}